package com.bulkmail.sender;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XmlParserReader {

	private List<String> elements = new ArrayList<String>();

	public XmlParserReader(String location) {
		initialization(location);
	}

	private void initialization(String location) {
		try {

			File fXmlFile = new File(location);
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(fXmlFile);

			doc.getDocumentElement().normalize();

			NodeList nList = doc.getElementsByTagName("property");
			for (int temp = 0; temp < nList.getLength() - 1; temp++) {
				Node nNode = nList.item(temp);
				if (nNode.getNodeType() == Node.ELEMENT_NODE) {

					Element elem = (Element) nNode;
					this.elements.add(elem.getAttribute("value"));
				}
			}
			Node nodeprim = doc.getElementsByTagName("value").item(0)
					.getFirstChild();
			this.elements.add(nodeprim.getNodeValue());

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public DataSession populateDataSession(DataSession dataSession) {
		List<String> temp = new ArrayList<String>();
		
		dataSession.setServer(elements.get(0));
		dataSession.setPort(elements.get(1));
		dataSession.setUsername(elements.get(2));
		dataSession.setPassword(elements.get(3));
		dataSession.setFrom(elements.get(7));
		String[] toMany = elements.get(8).split(";");
		for(int i = 0; i < toMany.length; i++){
			temp.add(toMany[i]);
		}		
		dataSession.setTo(temp);
		dataSession.setSubject(elements.get(9));
		dataSession.setMessage(elements.get(10));

		return dataSession;

	}
}